from fastapi import APIRouter, Depends, HTTPException, Query
from typing import List, Optional
from sqlalchemy.ext.asyncio import AsyncSession
from modules.system.services.table_service import table_service
from modules.system.schemas.table_schemas import (
    TableBasicInfo, TableStructureInfo, TableColumnInfo,
    TableListResponse, DatabaseSummaryInfo, TableSearchRequest,
    TableColumnSearchRequest, TableOptionInfo
)
from database.database import get_db
from core.base.api_mode import ApiResponse, api_success, api_error

router = APIRouter()

@router.get("/list", response_model=ApiResponse[TableListResponse], summary="获取表列表")
async def get_tables_list(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页大小"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    table_type: Optional[str] = Query(None, description="表类型：system/business"),
    db: AsyncSession = Depends(get_db)
):
    """
    获取数据库表列表，支持分页和搜索
    """
    try:
        request = TableSearchRequest(
            page=page,
            size=size,
            keyword=keyword,
            table_type=table_type
        )
        result = await table_service.get_tables_with_pagination(db, request)
        return api_success(data=result)
    except Exception as e:
        return api_error(message=f"获取表列表失败: {str(e)}")


@router.get("/structure/{table_name}", response_model=ApiResponse[TableStructureInfo], summary="获取表结构详情")
async def get_table_structure(table_name: str, db: AsyncSession = Depends(get_db)):
    """
    获取指定表的详细结构信息，包括列、索引、外键等
    """
    try:
        result = await table_service.get_table_structure(db, table_name)
        return api_success(data=result)
    except HTTPException:
        raise
    except Exception as e:
        return api_error(message=f"获取表结构失败: {str(e)}")


@router.get("/columns/{table_name}", response_model=ApiResponse[List[TableColumnInfo]], summary="获取表列信息")
async def get_table_columns(
    table_name: str,
    keyword: Optional[str] = Query(None, description="列名搜索关键词"),
    db: AsyncSession = Depends(get_db)
):
    """
    获取指定表的列信息，支持按列名搜索
    """
    try:
        request = TableColumnSearchRequest(
            table_name=table_name,
            keyword=keyword
        )
        result = await table_service.get_table_columns(db, request)
        return api_success(data=result)
    except HTTPException:
        raise
    except Exception as e:
        return api_error(message=f"获取表列信息失败: {str(e)}")


@router.get("/search", response_model=ApiResponse[List[TableOptionInfo]], summary="搜索表名")
async def search_tables(keyword: str = Query(..., description="搜索关键词"), db: AsyncSession = Depends(get_db)):
    """
    根据关键词搜索表名
    """
    try:
        result = await table_service.search_tables(db, keyword)
        return api_success(data=result)
    except Exception as e:
        return api_error(message=f"搜索表名失败: {str(e)}")


@router.get("/summary", response_model=ApiResponse[DatabaseSummaryInfo], summary="获取数据库概要信息")
async def get_database_summary(db: AsyncSession = Depends(get_db)):
    """
    获取数据库概要统计信息
    """
    try:
        result = await table_service.get_database_summary(db)
        return api_success(data=result)
    except Exception as e:
        return api_error(message=f"获取数据库概要信息失败: {str(e)}")


@router.get("/all", response_model=ApiResponse[List[TableOptionInfo]], summary="获取所有表名")
async def get_all_tables(db: AsyncSession = Depends(get_db)):
    """
    获取数据库中所有表名
    """
    try:
        result = await table_service.get_all_tables(db)
        return api_success(data=result)
    except Exception as e:
        return api_error(message=f"获取所有表名失败: {str(e)}")